// 1.导入Redis模块
const { createClient } = require('redis')
const { REDIS_CONFIG } = require('../config/db')

// 2.创建连接并监听错误
const client = createClient(REDIS_CONFIG)
client.on('error', (error) => {
  console.error('Redis Client Error', error)
})

// 3.建立Redis连接
client.connect().then(r => 'Redis Connected' + r)

// 4.封装保存数据和获取数据的方法
const setRedis = async (key, value) => {
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  await client.set(key, value)
}
const getRedis = async key => {
  const value = await client.get(key)
  try {
    return JSON.parse(value)
  } catch (e) {
    return value
  }
}

module.exports = {
  setRedis,
  getRedis
}
